<template> 
    <div>
        <el-card shadow="never">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>新增商品</el-breadcrumb-item>            
            </el-breadcrumb>
        
        <el-form ref="form" :model="form" label-width="80px" class="form-container" :rules="rules">
            <el-form-item label="图片" prop='imageList'>
                <el-card>
                    <el-upload class="upload-demo" action=''
                     :before-upload="beforeUpload" :on-remove="removeHandler" :file-list="form.imageList" list-type="picture"
                     :http-request="uploadFile" multiple >
                        <el-button size="small" type="primary">选择上传</el-button>
                        <div slot="tip" class="el-upload__tip">图片大小不超过3M，最多6张，建议使用方形图片</div>
                    </el-upload>
                </el-card>
            </el-form-item>
            <el-form-item label="商品名称" prop='name'>
                <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
             <el-form-item label="描述" prop='desc'>
                <el-input type="textarea" v-model="form.desc" placeholder="请输入商品描述"></el-input>
            </el-form-item>
            <el-form-item label="价格类型 " >
                <el-radio-group v-model='price_radio' @change="changePriceRadio">
                    <el-radio label="single" > 单一规格 </el-radio>
                    <el-radio label="multiple" > 多种规格</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="规格" prop="specList" v-if="price_radio == 'multiple'">
                <el-card class="box-card">
                    <el-table :data="form.specList" v-model="form.specList" style="width: 100%">
                        <el-table-column label="规格名称" width="180">
                            <template slot-scope="scope">                                
                                <el-input type='text' v-model="scope.row.name" placeholder="规格名称"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="价格(元)" width="180">
                            <template slot-scope="scope">                                
                                <el-input type="number" v-model="scope.row.price" placeholder='0.00'></el-input>
                            </template>
                        </el-table-column>
                         <el-table-column label="配送费(元)" width="180">
                            <template slot-scope="scope">                              
                                <el-input type="number" v-model="scope.row.mealfee" placeholder='0.00'></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="库存" width="360">
                            <template slot-scope="scope">
                                <el-radio v-model="scope.row.inventoryType" label="1">无限库存</el-radio>
                                <el-radio v-model="scope.row.inventoryType" label="2">自定义库存</el-radio>
                                <el-input type="number" v-model="scope.row.inventoryNumber" size="mini" style="width:100px" v-show="scope.row.inventoryType == 2">
                                    <div slot="suffix" style="text-align:center;">份</div>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini"  type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="mini" @click="createNewSpec">新增规格</el-button>
                 </el-card>
            </el-form-item>
            <el-form-item label="价格(元)" v-else-if="price_radio == 'single'" prop='price'>
                <el-card>
                    单价 <el-input type="number" v-model="form.price" min="0" max="9999" placeholder="请输入商品单价"></el-input>                
                    配送费 <el-input type="number" v-model="form.mealfee" min="0" max="9999" placeholder="请输入配送费"></el-input>

                    库存方式：
                    <el-radio v-model="form.inventoryType" label='0'>无限库存</el-radio>
                    <el-radio v-model="form.inventoryType" label='1'>自定义库存</el-radio>
                    <el-input type="number" v-model="form.inventoryNumber" size="mini" style="width:150px" v-show="form.inventoryType == 1" placeholder="请输入库存量">
                        <div slot="suffix" style="text-align:center;">份</div>
                    </el-input>
                </el-card>
            </el-form-item>
            <el-form-item label="属性">
                <el-card>
                    <el-table :data="form.properties"  style="width: 100%">
                        <el-table-column label="属性名称" width="180">
                                <template slot-scope="scope">                                
                                    <el-input type="text" v-model="scope.row.propName" placeholder="如：辣度" size="mini" style="width:100px;" >                                    
                                    </el-input>
                                </template>
                        </el-table-column>
                        <el-table-column label="属性细分（至少填写两个）" width="720">
                                <template slot-scope="scope">                                
                                    <el-input type="text" size="mini" v-for='(detail,pindex) in scope.row.details' :key="pindex" v-model="scope.row.details[pindex]" style="width:100px; margin:0 2px;" :placeholder="pindex==0?'如：不辣':''"></el-input>
                                </template>
                        </el-table-column>
                        <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button size="mini"  type="danger" @click="handlePropertyDelete(scope.$index, scope.row)">删除</el-button>
                                </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="mini" @click="createNewProperty">增加商品属性</el-button>
                </el-card>
            </el-form-item>
            <el-form-item label="分组" prop="groupNames">
                <el-card>
                    <!-- <el-checkbox-group v-model="form.groupIds">
                        <el-checkbox :label="group.name" v-for="(group,gIndex) in groups" :key="gIndex" name="type" :true-label="group.id" ></el-checkbox>
                    </el-checkbox-group> -->
                    <el-select v-model="form.groupIds" multiple placeholder="请选择">
                        <el-option v-for="(group,gIndex) in groups" :key="gIndex" :label="group.name"   :value="group.id">
                        </el-option>
                    </el-select>
                    <el-button type="primary" style="display:inline-block; margin-top:10px" size="mini" @click="createNewGroup">增加分组</el-button>
                    <label class="group-text">商品需要放入分组后，才会展示给顾客</label>
                </el-card>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit('form')">完成</el-button>
                <el-button type="reset" @click="cancel('form')">取消</el-button>
                <el-button type="default" @click="resetForm('form')">完成,继续添加下一个</el-button>
            </el-form-item>
        </el-form>
        </el-card>
    </div>
</template>

<script>

// 引入LeanCloud存储
var AV = require('leancloud-storage');

import Goods from '../../../models/Goods.js'
import GoodsGropusMap from '../../../models/GoodsGroupsMap.js'


export default {
    data(){
        return {
            typeId:this.$route.params.id, //商品类型
            price_radio:'single',
            form: {
                name: '',
                desc: '',
                imageList:[],
                specList:[],                
                groupIds:[],//当前的分组
                properties:[],//属性列表
                
                price:'', //价格
                mealfee:'', //配送费
                inventoryType:'0', //库存方式
                inventoryNumber:'',//库存量

            },           
            groups:[],//分组数据
            fileReader:'',
            rules: {
                name:[
                    {required:true,message:'请输入商品名称',trigger:'blur'},
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                desc:[
                    { message:'请输入商品描述',trigger:'blur'}
                ],
                imageList:[
                    {type: 'array', required:true,message: '请选择图片' ,trigger:'blur'}
                ],
                specList:[
                    { type: 'array', required: true, message: '请至少添加一个规格', trigger: 'blur'}

                ],
                groupIds:[
                    { type: 'array', required: true, message: '请至少选择一个分组', trigger: 'blur'}
                ],
                price:[
                    {required:true,message:'请输入商品价格',trigger:'blur'},
                ]

            },
            // shopId
            shop_id : localStorage.getItem('shop_id')
        }
    },
    mounted(){
        this.fileReader = new FileReader()
        this.groups = this.$route.params.groups
    },
    methods:{
        changePriceRadio(value){
            // console.log(value)
            this.price_radio = value
        },
        handlePreview(){
            console.log("handlePreview")
        },
        handleRemove(){
            console.log("handleRemove")
        },
        createNewSpec(){
            this.form.specList.push({
                inventoryType:'1',
            })
        },
        createNewProperty(){
            this.form.properties.push(
                {propName:'',details:['','','','','','']
            })

        },
        createNewGroup(){
            this.$prompt('请输入分组名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputErrorMessage: '分组名称不能为空'
                }).then(({ value }) => {
                    //创建分组
                    this.groups.push(
                        {name:value}
                    )                    
                    this.$message({
                        type: 'success',
                        message: '新建分组成功: ' + value
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消新建分组'
                });       
            }); 
        },
        handleDelete(index, row){
            this.form.specList.splice(index,1)
        },
        handlePropertyDelete(index,row){
            this.form.properties.splice(index,1)
        },
        onSubmit(formName,next){
            //判断输入是否合法
            this.$refs[formName].validate((valid) => {
                if (!valid) {                    
                    //console.log('error submit!!');
                    this.$message.error('输入项有错误，请核对错误项（红色）之后重试')
                    return false;
                }

                let nGoods = new Goods()
                


                nGoods.name = this.form.name
                nGoods.desc = this.form.desc
                nGoods.imageList = this.form.imageList
                nGoods.specList = this.form.specList
                //nGoods.groups = this.form.groupIds
                // 插入分组数据
                
                // nGoods.groups = groups
                // console.log(nGoods.groups)

                nGoods.properties = this.form.properties
                nGoods.price = this.form.price
                nGoods.mealfee = this.form.mealfee
                nGoods.inventoryType = this.form.inventoryType
                nGoods.inventoryNumber = this.form.inventoryNumber
                nGoods.shopId = AV.Object.createWithoutData('Seller', this.shop_id); //设置店铺ID//this.shop_id
                
                // console.log(nGoods)

                nGoods.save().then( (dGoods)=> {
                    debugger;
                    let groups = []
                    console.log(this.form.groupIds)
                    this.form.groupIds.forEach(element => {
                        var goodsGroupsMap = new GoodsGropusMap();
                        goodsGroupsMap.goods = dGoods
                        
                        goodsGroupsMap.group = AV.Object.createWithoutData('Groups',element)
                        goodsGroupsMap.save() //保存产品与类型的对应关系
                    });

                    this.$message('商品创建成功！');
                    if(!next){
                        // 是否回退页面
                         this.$router.push({ name: 'goods'})
                    }

                }, (error) =>{
                    this.$message.error(error);
                });

            });
        },
        resetForm(formName) {  //完成，继续下一步操作
            this.onSubmit(formName,true) //true 是否跳转下一个操作
            this.$refs[formName].resetFields();
        },
        cancel(){
           //取消添加操作
            this.$router.push({ name: 'goods'})
        },
        uploadFile(options){
            let file = options.file
            let fileName = file.name
            if (file) {
                this.fileReader.readAsDataURL(file)
            }
            let that = this;
            this.fileReader.onload = () => {
                let base64Str = this.fileReader.result
                var data = {base64:base64Str}
                var nfile = new AV.File(fileName,data)
                // nfile.setACL()
                nfile.save({
                    onprogress:function (e)  {
                        console.log('file upload progress:'+e)
                        // { loaded: 1234, total: 2468, percent: 50 }
                    },
                }).then(function(dfile){
                    console.log(dfile)//
                    that.form.imageList.push({
                        name:fileName,url:dfile.url(),dfile,id:dfile.id
                    })
                }).catch(error=>{
                    console.error(error)
                })
            }

        },
        removeHandler (file, fileList) {
            // debugger;
            let that = this
           
            console.log('current file list ==>', this.fileList)
            
            // 删除数据库中的缓存文件
            var file = AV.File.createWithoutData(file.id);
            if(!file) return;
            file.destroy().then(function (success) {
                    let index = that.form.imageList.indexOf(file.id)
                    that.form.imageList.splice(index, 1)
                    that.$message('图片删除成功')
                }, function (error) {
                    that.$message('图片删除错误') //需要给文件添加用户权限，有权限的用户才能删除
            });
        },
        beforeUpload (file) {
            const isLt5M = file.size < 2 * 1024 * 1024
            if (this.form.imageList.length >= 6) {
                this.$message.error('At most 6 files')
                return false
            }
            if (!isLt5M) {
                this.$message.error('The max size is 2MB')
                return false
            }
        }

    }
}
</script>

<style lang="scss" scoped>
.el-upload__tip{
    font-size: 10px;
    line-height: 12px;
    color: #ccc;
    //border-left: 2px solid skyblue;
    margin-top: 10px;
}
.group-text{
    font-size: 10px;
    line-height: 12px;
    color: #ccc;
    //border-left: 2px solid skyblue;
    margin-top: 10px;
    text-indent: 2em;
}
.el-upload-list {
  /* text-align: center; */
  margin: 0 auto;
  padding: 0 16px;
  max-width: 500px;
}
.el-upload-list__item{
    max-width: 100px;
}
.form-container{
    margin-top: 10px;
}
</style>

